#!/usr/bin/env python
#
# Copyright 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import logging
import os

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp import util


GADGET_PATH = '/()([a-z0-9-]+)\.xml'
DEV_GADGET_PATH = '/dev/([a-z]+)/([a-z0-9-]+)\.xml'


GADGET_CONFIGS = {
    '': {'CONTENT_HOST': 'global-learning-portal-2.appspot.com'},
    'local': {'CONTENT_HOST': 'localhost:8080'},
    'local1': {'CONTENT_HOST': 'localhost:8081'},
    'local2': {'CONTENT_HOST': 'localhost:8082'},
    'local3': {'CONTENT_HOST': 'localhost:8083'},
    'local4': {'CONTENT_HOST': 'localhost:8084'},
    'local5': {'CONTENT_HOST': 'localhost:8085'},
    'local6': {'CONTENT_HOST': 'localhost:8086'},
}


class GadgetHandler(webapp.RequestHandler):

  def get(self, config_name, gadget_name):
    gadget_config = GADGET_CONFIGS.get(config_name, None)
    if not gadget_config:
      logging.error('No such config %s', config_name)
      self.error(404)
      return

    gadget_path = os.path.join('gadgets', gadget_name + '.xml')
    self.response.headers['content-type'] = 'text/xml'
    self.response.out.write(template.render(gadget_path, {
        'config': gadget_config}))


def main():
  util.run_wsgi_app(application)


if __name__ == '__main__':
  application = webapp.WSGIApplication([(GADGET_PATH, GadgetHandler),
                                        (DEV_GADGET_PATH, GadgetHandler),
                                        ],
                                       debug=True)
  main()
